import request from '@/api/index'
const state = {
    //用户信息
    userInfo: "",
    //用户歌单
    userSongsMenu: [],
    //用户喜欢音乐列表
    userLikedMusic: []
}

const mutations = {
    getUserInfo: (state, payload) => {
        state.userInfo = payload
    },
    getUserSongsMenu: (state, payload) => {
        state.userSongsMenu = payload
    },
    getUserlikedMusic: (state, payload) => {
        state.userLikedMusic = payload
    },
    //用户喜欢、取消喜欢音乐后操作喜欢音乐列表增加删除该音乐
    todoMusic: (state, payload) => {
        if (payload.type === "喜欢") {
            state.userLikedMusic.unshift(payload.id)
        } else if (payload.type === "取消喜欢") {
            state.userLikedMusic.splice(
                state.userLikedMusic.indexOf(payload.id), 1
            )
        }
    }
}
const actions = {
    //获取用户信息
    async getUserInfo({ commit, dispatch }) {
        let userId = localStorage.getItem("userId");
        if (!userId) return
        const res = await request("/user/detail", { uid: userId })
        //存储用户信息
        commit("getUserInfo", res.profile)
        //获取用户歌单
        dispatch("getUserList")
        //获取用户喜欢音乐列表
        dispatch("getUserlikedMusic")
        //获取用户登入状态
        dispatch("getState")
    },
    //获取用户歌单
    async getUserList({ commit }) {
        let userId = localStorage.getItem("userId");
        const res = await request("/user/playlist", { uid: userId, timestamp: Date.now() })
        //存储用户歌单
        commit("getUserSongsMenu", res.playlist)
    },
    //获取用户喜欢音乐列表
    async getUserlikedMusic({ commit }) {
        let userId = localStorage.getItem("userId")
        const res = await request("/likelist", { uid: userId, timestamp: Date.now() })
        commit("getUserlikedMusic", res.ids)
    },
}


export default {
    state,
    mutations,
    actions,
}